/**
 * 
 */
package com.escriba.DAO;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.escriba.model.Person;




/**
 * @author Marco.Lobo
 *
 */
public class PersonDao {

	private Session sesion;
    private Transaction tx;
    
    private void startTransaction()/* throws HibernateException*/  {
    	try {
    		sesion = HibernateUtil.getSessionFactory().openSession();
    	
        tx = sesion.beginTransaction();
    	}catch (Exception e) {
			System.out.println(e);
			System.out.println(e.getMessage());
			System.out.println(e.getCause());
		}
    }
    
    private void handleException(HibernateException he) throws HibernateException {
        tx.rollback();
        throw new HibernateException("An error in the data acces layer", he);
    }
    
    public long guardaContacto(Person person) { 
        long id = 0;  

        try 
        { 
        	startTransaction(); 
            id = (Long)sesion.save(person); 
            tx.commit(); 
        }catch(HibernateException he) { 
            handleException(he);
            throw he; 
        }catch (Exception e) {
			System.out.println(e);
			System.out.println(e.getMessage());
			System.out.println(e.getCause());
		}finally 
        { 
            sesion.close(); 
        }  
        return id; 
    }
    
    public void updatePerson(Person person) throws HibernateException { 
        try 
        { 
            startTransaction(); 
            sesion.update(person); 
            tx.commit(); 
        }catch (HibernateException he) 
        { 
            handleException(he); 
            throw he; 
        }finally 
        { 
            sesion.close(); 
        } 
    }
    

    public void deletePerson(Person person) throws HibernateException { 
        try 
        { 
            startTransaction(); 
            sesion.delete(person); 
            tx.commit(); 
        } catch (HibernateException he) 
        { 
            handleException(he); 
            throw he; 
        }finally 
        { 
            sesion.close(); 
        } 
    }
    
    public Person getPerson(int idPerson) throws HibernateException { 
    	Person person = null;  

        try 
        { 
            startTransaction(); 
            person = (Person) sesion.get(Person.class, idPerson); 
        } finally 
        { 
            sesion.close(); 
        }  
        return person; 
    }
    
    public List<Person> getPersons() throws HibernateException { 
        List<Person> persons = null;  
        
        try 
        { 
            startTransaction(); 
            persons = sesion.createQuery("from Person").list(); 
        }finally 
        { 
            sesion.close(); 
        }  

        return persons; 
    }
}
